package com.macro.mall.portal.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.UUID;
import com.macro.mall.common.api.CommonResult;
import com.macro.mall.portal.dto.MinioUploadDto;
import io.minio.MinioClient;
import io.minio.policy.PolicyType;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.coobird.thumbnailator.Thumbnails;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileWriter;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by macro on 2019/12/25.
 */
@Api(tags = "MinioController", description = "MinIO对象存储管理")
@Controller
@RequestMapping("/minio")
public class MinioController {

    @Autowired
    private HttpServletRequest request;

    private static final Logger LOGGER = LoggerFactory.getLogger(MinioController.class);
    @Value("${minio.endpoint}")
    private String ENDPOINT;
    @Value("${minio.bucketName}")
    private String BUCKET_NAME;
    @Value("${minio.accessKey}")
    private String ACCESS_KEY;
    @Value("${minio.secretKey}")
    private String SECRET_KEY;

    @Value("${user.tempdir}")
    private String tempdir;

    @ApiOperation("文件上传")
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult upload(@RequestParam("file") MultipartFile file) {
        try {

            if(file.getSize()>10*1024*1024){
                return CommonResult.failed("文件太大");
            }
            String extName=FileUtil.extName(file.getOriginalFilename());

            //创建一个MinIO的Java客户端
            MinioClient minioClient = new MinioClient(ENDPOINT, ACCESS_KEY, SECRET_KEY);
            boolean isExist = minioClient.bucketExists(BUCKET_NAME);
            if (isExist) {
                LOGGER.info("存储桶已经存在！");
            } else {
                //创建存储桶并设置只读权限
                minioClient.makeBucket(BUCKET_NAME);
                minioClient.setBucketPolicy(BUCKET_NAME, "*.*", PolicyType.READ_ONLY);
            }
            String filename = file.getOriginalFilename();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");

            String randomName= UUID.randomUUID().toString().replace("-","");
            // 设置存储对象名称
            String objectName = sdf.format(new Date()) + "/" + randomName+"."+extName;
            InputStream inputStream=null;
            if((extName.toLowerCase().equals("jpg")||extName.toLowerCase().equals("png"))&&file.getSize()>1024*200) {
                File toFile=compressImge(file);
                inputStream=FileUtil.getInputStream(toFile);
                FileUtil.del(toFile);
            }else {
                inputStream= file.getInputStream();
            }
            // 使用putObject上传一个文件到存储桶中
            minioClient.putObject(BUCKET_NAME, objectName,inputStream , file.getContentType());
            LOGGER.info("文件上传成功!");
            inputStream.close();
            MinioUploadDto minioUploadDto = new MinioUploadDto();
            minioUploadDto.setName(filename);
            minioUploadDto.setUrl(ENDPOINT + "/" + BUCKET_NAME + "/" + objectName);
            return CommonResult.success(minioUploadDto);
        } catch (Exception e) {
            LOGGER.info("上传发生错误: {  }！", e.getMessage());
        }
        return CommonResult.failed();
    }

    @ApiOperation("文件删除")
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult delete(@RequestParam("objectName") String objectName) {
        try {
            MinioClient minioClient = new MinioClient(ENDPOINT, ACCESS_KEY, SECRET_KEY);
            minioClient.removeObject(BUCKET_NAME, objectName);
            return CommonResult.success(null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return CommonResult.failed();
    }

    @ApiOperation("文件上传测试")
    @RequestMapping(value = "/uploadtest", method = RequestMethod.POST)
    @ResponseBody
    public void  fileHandler(MultipartFile file) throws  Exception{
        String uploaddir = tempdir + "/img/tmp";
        if(!FileUtil.isDirectory(uploaddir)) {
            FileUtil.mkdir(uploaddir);
        }
        String extName=FileUtil.extName(file.getOriginalFilename());
        String randomName= UUID.randomUUID().toString().replace("-","");
        String pathName = File.separator + randomName + "." + extName;
        String filePathName = uploaddir + File.separator + pathName;
        //判断文件保存是否存在
        File tempfile = new File(filePathName);
        if (tempfile.getParentFile() != null || !tempfile.getParentFile().isDirectory()) {
            //创建文件
            tempfile.getParentFile().mkdirs();
        }
        file.transferTo(tempfile);

        String topathName = File.separator + randomName +"_small"+ "." + extName;
        String tofilePathName = uploaddir + File.separator + topathName;
        //判断文件保存是否存在
        File totempfile = new File(tofilePathName);

        FileUtil.file(tofilePathName);

        //图片尺寸不变，压缩图片文件大小outputQuality实现,参数1为最高质量
        Thumbnails.of(tempfile).scale(1f).outputQuality(0.25f).toFile(totempfile);

        //FileUtil.del(tempfile);

    }

    private File compressImge(MultipartFile file) throws Exception{
        String extName=FileUtil.extName(file.getOriginalFilename());
        String uploaddir = tempdir + "/img/tmp";
        if (!FileUtil.isDirectory(uploaddir)) {
            FileUtil.mkdir(uploaddir);
        }
        String randomName = UUID.randomUUID().toString().replace("-", "");
        String pathName = File.separator + randomName + "." + extName;
        String filePathName = uploaddir + File.separator + pathName;
        //判断文件保存是否存在
        File tempfile = new File(filePathName);
//        if (tempfile.getParentFile() != null || !tempfile.getParentFile().isDirectory()) {
//            //创建文件
//            tempfile.getParentFile().mkdirs();
//        }
        file.transferTo(tempfile);
        String topathName = File.separator + randomName + "_small" + "." + extName;
        String tofilePathName = uploaddir + File.separator + topathName;
        //判断文件保存是否存在
        File totempfile = new File(tofilePathName);
        FileUtil.file(tofilePathName);
        //图片尺寸不变，压缩图片文件大小outputQuality实现,参数1为最高质量
        Thumbnails.of(tempfile).scale(0.8f).outputQuality(0.8f).toFile(totempfile);
        FileUtil.del(tempfile);
        return totempfile;
    }
}
